/**
 * 作者：白茂林
 * 时间：2017-06-15
 * 描述：登录
 */
mui.init();
/*声明 view 变量*/
var input_account = mui('#input_account')[0]; //用戶名
var input_password = mui('#input_password')[0]; //密码
var span_rememberPwd = mui("#span_rememberPwd")[0]; //记住密码
var div_register = mui("#div_register")[0]; //账号注册
var wgtVer = ''; //版本号
var appName = ''; //应用名称
var phoneID = ""; //手机唯一标识
var osName = ""; //系统平台名称
var clientid = ""; //推送唯一标识
var user = null;
var newVersion_fjid = "";
window.addEventListener("reloadView", function() {
	window.location.reload();
})

mui.plusReady(function() {
	//getLocalVer() // 获取本地应用资源版本号
	getPushInfo() //获取推送的clientid
	//竖屏锁定
	plus.screen.lockOrientation("portrait-primary");
	//关闭 app入场动画
	setTimeout(function() {
		plus.navigator.closeSplashscreen();
	}, 600);
	//判断是否是记住密码，并做相应的操作
	isRememberPwd();
	//初始化监听
	initListener();
	//重写返回事件，实现一秒内点两次返回才退出程序
	rebuildBack();
});

function initListener() {
	//记住密码选框的监听事件
	span_rememberPwd.addEventListener('tap', function() {
		//判断是否选中，选中是true
		var isSelect = span_rememberPwd.classList.contains('icon-check-selected');
		//若当前是选中状态则该为未选中状态，反之当前为未选中状态则改为选中状态
		if(isSelect) {
			checkRemoveSelect(span_rememberPwd)
		} else {
			checkSelect(span_rememberPwd)
		}
	});
	//登录监听
	mui('#div_login')[0].addEventListener('tap', function(event) {
		//解决ios概率性出现弹框问题
		//		if(this.classList.contains("active")){
		if(mui.os.ios) {
			setTimeout(function() {
				input_account.blur(); //使输入框失去焦点
				input_password.blur(); //使输入框失去焦点
			}, 30)
		}
		var account = input_account.value; //用户名
		var password = input_password.value; //密码
		if(account == null || account.length == 0 || password == null || password.length == 0) {
			mui.toast("用户名或密码不能为空");
		} else {
			setAccount(account);
			var isSelect = span_rememberPwd.classList.contains('icon-check-selected');
			if(isSelect) {
				setPassword(password);
			}
			login(account, password); //登陆函数，进行登陆请求
		}
		//		}
	});

	div_register.addEventListener('tap', function(event) {
		jumpTo('_www/module/register/register.html', 'register.html', jumpPopIn, {

		});
	});
	//人员角色选择
	mui("#div_role_check").on("tap", ".div_role_item", function() {
		var roleId = this.getAttribute("roleid");
		console.log(roleId)
		mui.later(function() {
			mui("#div_role_check")[0].classList.add("mui-hidden");
		}, 100)
		//		roleSelect(roleId,false);
	})
	//版本更新
	mui("#div_upload_btn")[0].addEventListener("tap", function() {
		downloadNewApk(newVersion_fjid);
	})
	//关闭更新
	mui(".icon-clear")[0].addEventListener("tap", function() {

		mui("#div_upload")[0].classList.add("mui-hidden");
	})
};

/**
 * input失去焦点时去除空格
 * @param {Object} input
 */
function inputOnblur(input) {
	input.value = input.value.replace(/\s/g, ""); //去除文章中间空格
}

//重写返回事件，实现一秒内点两次返回才退出程序
function rebuildBack() {
	var backButtonPress = 0;
	mui.back = function(event) {
		backButtonPress++;
		if(backButtonPress > 1) {
			plus.runtime.quit(); //退出应用
		} else {
			plus.nativeUI.toast('再按一次退出应用');
		}
		//点击返回一秒后将标志位nBackButtonPress清零
		setTimeout(function() {
			backButtonPress = 0;
		}, 1000);
		return false;
	};
}
/**
 * 判断是否记住密码，并做相应操作
 */
function isRememberPwd() {
	//从本地获取登陆用户名
	var account = getAccount();
	//从本地获取是否记住密码
	var isRememberPwd = getIsRememberPwd();
	//给用户名输入框赋值   
	input_account.value = account;
	if(isRememberPwd == "true") {
		//记住密码,将选框的字体图标替换为选中状态
		checkSelect(span_rememberPwd);
		//从本地获取登陆密码
		var password = getPassword();
		//给密码输入框赋值   
		input_password.value = password;
	} else {
		//不记住密码，将选框的字体图标替换为未选中状态
		checkRemoveSelect(span_rememberPwd);
	}
};

/**
 * 登录
 * @param {Object} account  用户名
 * @param {Object} password  密码
 */
function login(account, password) {
	var param = { //网络请求传递的参数
		username: account,
		password: faultylabs.MD5(password),
		pageStyle: "",
		logined: ""
	};
	plus.nativeUI.showWaiting();
	//执行ajax
	console.log(JSON.stringify(param))
	ajax(CHECK_LOGIN, param,
		function(data) {
			if(data.successful) { //登陆成功
				//保存用户信息
				user = data.resultValue;
				getPushInfo();
				if(span_rememberPwd.classList.contains('icon-check-selected')) {
					setIsRememberPwd('true');
				} else {
					setIsRememberPwd('false');
				}
				user.roles = data.resultValue[0];
				setUserModel(user);
				jumpTo("../index/index.html", "index.html", jumpPopIn, {
					roles: data.resultValue
				});
				//getPersonMessage(data.resultValue.persId)
			} else {
				plus.nativeUI.closeWaiting();
				mui.toast(data.resultHint); //弹出后台返回的登录操作结果，成功或者失败或者失败原因
			}
		},
		function() {
			plus.nativeUI.closeWaiting();
		}
	);
};

/**
 * 将选择框置为选中
 * @param {Object} dom
 */
function checkSelect(dom) {
	dom.classList.remove('icon-check-unselected');
	dom.classList.add('icon-check-selected');
//	dom.style.color = "#009FA8";
    dom.style.color = "#FDFDFD";
};

/**
 * 将选择框置为未选中
 * @param {Object} dom
 */
function checkRemoveSelect(dom) {
	dom.classList.remove('icon-check-selected');
	dom.classList.add('icon-check-unselected');
	dom.style.color = "#dbdbdb";
};
/**
 * 获取本地应用资源版本号等
 */
function getLocalVer() {
	phoneID = plus.device.uuid;
	localStorage.setItem("phoneID", phoneID)
	osName = plus.os.name
	localStorage.setItem("osName", osName)
	plus.runtime.getProperty(plus.runtime.appid, function(inf) {
		wgtVer = inf.version;
		localStorage.setItem("Ver", wgtVer);
		appName = inf.name;
		localStorage.setItem("appName", appName)
		getApkVersion(wgtVer);
	});
}

/**
 * 获取推送id
 */
function getPushInfo() {
	var info = plus.push.getClientInfo();
	console.log(JSON.stringify(info));
	clientid = info.clientid;
	localStorage.setItem("clientID", clientid);
}

/**
 * 获取人员角色信息
 * @param {Object} persId
 * @param {Object} successCallBack
 */
function getPersonMessage(persId) {
	var params = {
		params: {
			persId: persId,
			mobileId: clientid,
			bbh: wgtVer
		}
	}
	console.log(JSON.stringify(params));
	ajax(GET_PERSON_ROLE, params, function(data) {
		if(data.successful == "true") {
			//			if(data.resultValue.length === 1){
			//				
			//				roleSelect(data.resultValue[0],true);
			//			}else{
			//				selectPersonRole(data.resultValue);
			//				plus.nativeUI.closeWaiting();
			//			}
			plus.nativeUI.closeWaiting();
			if(data.successful === "true") {
				mui.toast("登录成功");
				if(span_rememberPwd.classList.contains('icon-check-selected')) {
					setIsRememberPwd('true');
				} else {
					setIsRememberPwd('false');
				}
				user.roles = data.resultValue[0];
				setUserModel(user);
				jumpTo("../index/index.html", "index.html", jumpPopIn, {
					roles: data.resultValue
				});
			} else {
				mui.toast(data.resultHint)
			}
		} else {
			plus.nativeUI.closeWaiting();
			mui.toast(data.resultHint);
		}
	}, function() {
		mui.toast("请求失败")
	})
}

function selectPersonRole(roles) {
	var htmlStr = "";
	roles.forEach(function(item, index) {
		var roleName = "";
		if(item === PERSON_ROLE_CODE.OFFICE) {
			roleName = "技术监督办公室"
		} else if(item === PERSON_ROLE_CODE.OFFICE_PROVINCE) {
			roleName = "省技术监督办公室"
		} else if(item === PERSON_ROLE_CODE.TEAM) {
			roleName = "技术监督班组"
		} else if(item === PERSON_ROLE_CODE.COMPANY) {
			roleName = "技术监督省公司"
		} else {
			roleName = "暂无此角色"
		}
		htmlStr += '<div roleid="' + item + '" class="div_role_item FONT_F3 BG_C8">' + roleName + '</div>';
	})
	mui("#div_role_type")[0].innerHTML = htmlStr;
	mui.later(function() {
		mui("#div_role_check")[0].classList.remove("mui-hidden");
	}, 300)
}

/*
function roleSelect(xzjs,single){
	var param = {
		param: {
			xzjs: xzjs
		}
	}
	var resultValue = [];
	if(!single){
		plus.nativeUI.showWaiting();
	}
	resultValue.push(xzjs);
	ajax(ROLE_SELECT,param,function(data){
		plus.nativeUI.closeWaiting();
		if(data.successful === "true"){
			mui.toast("登录成功");
			if(span_rememberPwd.classList.contains('icon-check-selected')){
				setIsRememberPwd('true');
			}else{
				setIsRememberPwd('false');
			}
			user.roles = resultValue;
			setUserModel(user);
			
			jumpTo("../index/index.html", "index.html", jumpPopIn,{
				roles:resultValue
			});
		}else{
			mui.toast(data.resultHint)
		}
	},function(){
		mui.toast("请求失败");
		plus.nativeUI.closeWaiting();
	})
}
*/
/**
 * 检查更新
 */
function getApkVersion(appVersion) {
	var param = {
		params: {
			bbh: appVersion
		},
		sendByAngent: 'true'
	}
	console.log(appVersion)
	noNoticeAjax(GET_APK_VERSION, param, function(data) {
		console.log(JSON.stringify(data))
		//		if(!mui("#div_login")[0].classList.contains("active")){
		//			mui("#div_login")[0].classList.add("active");
		//		}
		if(data.successful == 'true') {
			console.log("有新版本更新")
			//			mui.popConfirm("检测到新版本，请更新","提示",function(){
			//				console.log("下载的附件id==========================="+data.resultValue.fjid)
			//				downloadNewApk(data.resultValue.fjid)	
			//			})
			console.log(JSON.stringify(data))
			var htmlStr = "";
			if(data.resultValue.gxnr.length > 0) {
				data.resultValue.gxnr.forEach(function(item, index) {
					htmlStr += '<li class="FONT_F5">' + item + '</li>'
				})

			} else {
				htmlStr += '<li class="FONT_F5">发现新版本' + data.resultValue.zxbbh + '</li>' +
					'<li class="FONT_F5">暂无说明</li>';
			}

			mui("#div_upload .div_upload_warn")[0].innerHTML = htmlStr;
			mui("#div_upload")[0].classList.remove("mui-hidden");
			newVersion_fjid = data.resultValue.fjid;
		} else {
			console.log("meiyou xinxixixn")
		}
	}, function() {
		//		if(!mui("#div_login")[0].classList.contains("active")){
		//			mui("#div_login")[0].classList.add("active");
		//		}
	})
}

/**
 * 下载更新包
 * @param {Object} fjid
 */
function downloadNewApk(fjid) {
	if(plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE) {
		mui.toast('当前网络不给力');
		return;
	}
	if(!mui("#div_upload")[0].classList.contains("mui-hidden")) {
		mui.later(function() {
			mui("#div_upload")[0].classList.add("mui-hidden")
		}, 300)
	}
	plus.nativeUI.showWaiting("下载更新文件...");
	//	var url = SERVER_ADDRESS+TASK_YJXZ+"?params={'fjid':'"+fjid+"'}&sendByAngent=true";
	var url = SERVER_ADDRESS + "/sdxsms/app/appDownload.do?type=apk&area=mengdong&sendByAngent=true";
	var task = plus.downloader.createDownload(url, {
		filename: "_downloads/sdxs.apk"
	}, function(task, status) {
		plus.nativeUI.closeWaiting();
		if(status == 200) {
			console.log(task.filename + "下载完成");
			installWgt(task.filename)
		} else {
			console.log(task.filename + "下载失败，错误" + status);
		}
	});
	task.addEventListener("statechanged", function(task, status) {
		switch(task.state) {
			case 1: //	此状态难以捕获
				console.log(task.filename + ': 准备就绪');
				break;
			case 2:
				console.log(task.filename + ': 已连接到服务器');
				break;
			case 3:
				//  			console.log(task.filename + ': ' + task.downloadedSize + '/' + task.totalSize);
				break;
			case 4:
				console.log(task.filename + ': ' + task.downloadedSize + '/' + task.totalSize);
				console.log(task.filename + ': 下载完成');
				break;
		}
	});
	task.start();
}

/**
 * 安装更新包
 * @param {Object} path
 */
function installWgt(path) {
	plus.nativeUI.showWaiting("安装中...");

	plus.runtime.install(path.trim(), {}, function() {
		plus.nativeUI.closeWaiting();
		plus.nativeUI.toast("安装成功！");
		plus.runtime.restart();
	}, function(e) {
		plus.nativeUI.closeWaiting();
		plus.nativeUI.toast("安装失败！");
		console.log(e.message);
	});
}

//(function($, document) {
//	$.popConfirm = function(content, title, successCallBack, errorCallBack) {
//		var popConfirmDiv = document.createElement("div"); //创建一个div蒙版	
//		popConfirmDiv.className = "mui-backdrop pop_confirm animated";
//		popConfirmDiv.innerHTML = '<div class="mui-popup mui-popup-in">' +
//			'<div class="mui-popup-inner">' +
//			'<div class="mui-popup-title"></div>' +
//			'<div class="mui-popup-content"></div>' +
//			'</div>' +
//			'<div class="mui-popup-buttons">' +
//			'<span class="mui-popup-button btn_sure">确定</span>' +
//			'</div>' +
//			'</div>';
//		$("body")[0].appendChild(popConfirmDiv); //创建的div蒙版加载到
//		$(".pop_confirm .mui-popup-title")[0].innerText = title;
//		$(".pop_confirm .mui-popup-content")[0].innerText = content;
//		//弹出框的确定按钮操作
//		$(".pop_confirm").on("tap", ".btn_sure", function() {
//			successCallBack();
//			setTimeout(function() {
//				$("body")[0].removeChild(popConfirmDiv);
//			}, 5);
//
//		})
//		$(".pop_confirm").on("tap", ".btn_cancel", function() {
//			errorCallBack ? errorCallBack() : "";
//			setTimeout(function() {
//				$("body")[0].removeChild(popConfirmDiv);
//			}, 5);
//		})
//	}
//})(mui, document)